<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'rd:apply:matMoreApply:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_Mat_apply"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'rd:apply:matMoreApply:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsM8RdApplyMatMoreApplyForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { MatMoreApply, matMoreApplySave, matMoreApplyForm } from '/@/api/m8/rd/apply/matMoreApply';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.apply.matMoreApply');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<MatMoreApply>({} as MatMoreApply);
  const loadingRef = ref(false);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增补料申请') : t('编辑补料申请'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单据编号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
      dynamicDisabled: true,
      required: true,
      // colProps: { lg: 12, md: 12 },
    },
    // {
    //   label: t('图名'),
    //   field: 'orderPic.picname',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   required: true,
    // },
    {
        label: t('图名'),
        field: 'orderPic.picname',
        fieldLabel: 'orderPic.picname',
        component: 'ListSelect',
        // componentProps: {
        //   selectType: 'orderPicSelect',
        //   onSelect:(item)=>{
        //     console.log(item);
        //   }
        // },
        componentProps: ({  formModel }) => {
          return {
            selectType: 'orderPicApplySelect',
            onSelect:(values)=>{
              formModel['orderPic.picno'] = values[0].orderPic.picno
              formModel['orderPic.picname'] = values[0].orderPic.picname


              formModel['orderPic.cmat'] = values[0].orderPic.cmat
              formModel['orderId'] = values[0].order.id
              formModel['picId'] = values[0].orderPic.id
              formModel['flowId'] = values[0].id
              formModel['operCode'] = values[0].oper.operCode
            }
          };
        },
        required: true,
    },

    {
      label: t('材料'),
      field: 'orderPic.cmat',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('规格'),
      field: 'xlSize',
      component: 'Input',
      componentProps: {
      },
      required: true,
    },
    {
      label: t('补料类型'),
      field: 'ctype',
      component: 'CheckboxGroup',
      componentProps: {
        dictType: 'm8_more_type',
      },
      required: true,

    },
    {
      label: t('flowId'),
      field: 'flowId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show: false,
    },
    {
      label: t('operCode'),
      field: 'operCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show: false,
    },
    {
      label: t('订单ID'),
      field: 'orderId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show: false,
    },
    {
      label: t('图纸ID'),
      field: 'picId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show: false,
    },
    {
      label: t('数量'),
      field: 'iqty',
      component: 'InputNumber',
      componentProps: {
        min:1
      },
      rules: [{ required: true }, { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('补料说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows:5
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('采购数'),
      field: 'sumPuQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      // rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      dynamicDisabled: true,
    },
    {
      label: t('入库数'),
      field: 'sumPuInQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      // rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      dynamicDisabled: true,
    },
    {
      label: t('停止补料'),
      field: 'bclose',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no',
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('申请人'),
      field: 'createBy',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('申请人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('申请时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
   
    
    
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await matMoreApplyForm(data);
    record.value = (res.matMoreApply || {}) as MatMoreApply;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      // const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      // console.log('submit', params, data, record);
      const res = await matMoreApplySave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
